package com.tb.shoop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.tb.v1.api.shoop.ISpPermissionService;
import com.tb.v1.api.shoop.ISpRoleService;
import com.tb.v1.api.vo.SpRoleVo;
import com.tb.v1.common.exception.CommonException;
import com.tb.v1.entity.SpPermission;
import com.tb.v1.entity.SpRole;
import com.tb.v1.result.ResultJson;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author: tangBin
 * @Date: 2020/7/14 0014 17:33
 * @Description:
 */
@RequestMapping("/v1")
@RestController
public class SpRoleController extends BaseController {

    @Reference
    private ISpRoleService spRoleService;

    @Reference
    private ISpPermissionService spPermissionService;

    /**
     * @return com.tb.v1.result.ResultJson<java.lang.Object>
     * @Author tangBin
     * @Description 根据角色获取角色下面所有权限菜单 列表
     * @Date 2020/7/20 0020 10:41
     * @Param []
     **/
    @RequestMapping("/roles")
    public ResultJson<Object> geRolesList() {
        List<SpRole> roleList = spRoleService.getAll();
        List resultList = new ArrayList();
        if (!roleList.isEmpty()) {
            List<SpPermission> onePermissionList = null;
            List<SpPermission> twoPermissionList = null;
            List<SpPermission> threePermissionList = null;
            List<Object> totalList = null;
            List<Object> twoList = null;
            Map roleMap = null;
            Map onePermissionMap = null;
            Map twoPermissionMap = null;
            Map paramsMap = new HashMap();
            for (SpRole role : roleList) {
                totalList = new ArrayList<>();
                paramsMap.put("psLevel", 0);
                paramsMap.put("psId", Arrays.asList(role.getPsIds().split(",")));
                //获取角色下面的权限管理 一级权限
                onePermissionList = spPermissionService.getRoleLevel(paramsMap);
                if (!onePermissionList.isEmpty()) {
                    for (SpPermission onePermission : onePermissionList) {
                        twoList = new ArrayList<>();
                        paramsMap.put("psLevel", 1);
                        paramsMap.put("psPid", onePermission.getPsId());
                        paramsMap.put("psId", Arrays.asList(role.getPsIds().split(",")));

                        //获取角色下面的权限管理 2级权限 就是列表
                        twoPermissionList = spPermissionService.getRoleLevel(paramsMap);
                        if (!twoPermissionList.isEmpty()) {
                            for (SpPermission twoPermission : twoPermissionList) {
                                paramsMap.put("psLevel", 2);
                                paramsMap.put("psId", Arrays.asList(role.getPsIds().split(",")));
                                paramsMap.put("psPid", twoPermission.getPsId());
                                //获取角色下面权限管理 2级权限 下面的 3级权限 就是 列表上面的操作方法权限
                                threePermissionList = spPermissionService.getRoleLevel(paramsMap);
                                twoPermissionMap = JSON.parseObject(JSON.toJSONString(twoPermission));
                                twoPermissionMap.put("children", threePermissionList);
                                twoList.add(twoPermissionMap);
                            }
                        }
                        onePermissionMap = JSON.parseObject(JSON.toJSONString(onePermission));
                        onePermissionMap.put("children", twoList);
                        totalList.add(onePermissionMap);
                    }
                }
                roleMap = JSON.parseObject(JSON.toJSONString(role), Map.class);
                roleMap.put("children", totalList);
                resultList.add(roleMap);
            }
        }
        return toResultModel("200", "成功", resultList);
    }

    /**
     * @return com.tb.v1.result.ResultJson<java.lang.Object>
     * @Author tangBin
     * @Description 根据角色删除权限方法
     * @Date 2020/7/20 0020 10:40
     * @Param [roleId, rightsId, psIds]
     **/
    @RequestMapping("/delete/{roleId}/{rightsId}")
    public ResultJson<Object> geDeleteRight(@PathVariable("roleId") String roleId,
                                            @PathVariable("rightsId") String rightsId,
                                            String psIds) throws Exception {
        if (StringUtils.isEmpty(roleId) && StringUtils.isEmpty(rightsId) && StringUtils.isEmpty(psIds)) {
            throw new CommonException("500", "参数为空");
        }
        SpRole spRole = new SpRole();
        List<String> list = Arrays.asList(psIds.split(","));
        List<String> arrayList = new ArrayList<String>(list);
        //移除删除的权限
        if (!arrayList.contains(rightsId)) {
            throw new CommonException("500", "该角色没有该权限,请刷新");
        }

        arrayList.remove(rightsId);
        spRole.setRoleId(Integer.valueOf(roleId));
        spRole.setPsIds(String.join(",", arrayList));
        Integer num = spRoleService.updateEntity(spRole);
        if (num == 0) {
            throw new CommonException("500", "删除权限失败");
        }
        Map onePermissionMap = null;
        List<Object> totalList = new ArrayList<>();
        List<SpPermission> twoPermissionList = null;
        List threePermissionList = null;
        List twoList = null;
        Map twoPermissionMap = null;
        Map paramsMap = new HashMap();
        paramsMap.put("psLevel", 0);
        paramsMap.put("psId", arrayList);
        //获取角色下面的权限管理 一级权限
        List<SpPermission> onePermissionList = spPermissionService.getRoleLevel(paramsMap);
        if (!onePermissionList.isEmpty()) {
            for (SpPermission onePermission : onePermissionList) {
                twoList = new ArrayList<>();
                paramsMap.put("psLevel", 1);
                paramsMap.put("psPid", onePermission.getPsId());
                paramsMap.put("psId", arrayList);
                //获取角色下面的权限管理 2级权限 就是列表
                twoPermissionList = spPermissionService.getRoleLevel(paramsMap);
                if (!twoPermissionList.isEmpty()) {
                    for (SpPermission twoPermission : twoPermissionList) {
                        paramsMap.put("psLevel", 2);
                        paramsMap.put("psId", arrayList);
                        paramsMap.put("psPid", twoPermission.getPsId());
                        //获取角色下面权限管理 2级权限 下面的 3级权限 就是 列表上面的操作方法权限
                        threePermissionList = spPermissionService.getRoleLevel(paramsMap);
                        twoPermissionMap = JSON.parseObject(JSON.toJSONString(twoPermission));
                        twoPermissionMap.put("children", threePermissionList);
                        twoList.add(twoPermissionMap);
                    }
                }
                onePermissionMap = JSON.parseObject(JSON.toJSONString(onePermission));
                onePermissionMap.put("children", twoList);
                totalList.add(onePermissionMap);
            }
        }
        return toResultModel("200", "成功", totalList);
    }

    /**
     * @return com.tb.v1.result.ResultJson<java.lang.Object>
     * @Author tangBin
     * @Description 根据角色分配权限方法
     * @Date 2020/7/20 0020 10:40
     * @Param [roleId, ids, psIds]
     **/
    @RequestMapping("/update/{roleId}")
    public ResultJson<Object> geUpdateRight(@PathVariable("roleId") String roleId,
                                            @RequestParam("ids") String[] ids,
                                            @RequestParam("psIds") String psIds) throws Exception {

        if (StringUtils.isEmpty(roleId) && StringUtils.isEmpty(ids)) {
            throw new CommonException("500", "参数为空");
        }
        SpRole spRole = new SpRole();
        List<String> list = null;
        if (!StringUtils.isEmpty(psIds)) {
            list = Arrays.asList(psIds.split(","));
        } else {
            list = new ArrayList<>();
        }
        List<String> arrayList = new ArrayList<String>(list);
        for (String str : ids) {
            if (!arrayList.contains(str)) {
                arrayList.add(str);
            }
        }
        spRole.setRoleId(Integer.valueOf(roleId));
        spRole.setPsIds(String.join(",", arrayList));
        Integer num = spRoleService.updateEntity(spRole);
        if (num == 0) {
            throw new CommonException("500", "分配权限失败");
        }
        return toResultModel("200", "分配权限成功");
    }

    /**
     * @return com.tb.v1.result.ResultJson<java.lang.Object>
     * @Author tangBin
     * @Description 根据角色id 删除角色信息
     * @Date 2020/7/20 0020 11:21
     * @Param [roleId]
     **/
    @RequestMapping("/delete/{roleId}")
    public ResultJson<Object> geDeleteRole(@PathVariable("roleId") String roleId) throws Exception {
        if (StringUtils.isEmpty(roleId)) {
            throw new CommonException("500", "参数为空");
        }
        Integer num = spRoleService.deleteEntity(Long.valueOf(roleId));
        if (num == 0) {
            throw new CommonException("500", "分配权限失败");
        }
        return toResultModel("200", "分配权限成功");
    }

    /**
     * @return com.tb.v1.result.ResultJson<java.lang.Object>
     * @Author tangBin
     * @Description 编辑角色信息
     * @Date 2020/7/20 0020 12:01
     * @Param [roleId]
     **/
    @RequestMapping("/update/info/{roleId}")
    public ResultJson<Object> geUpdateRole(@PathVariable("roleId") String roleId,
                                           String roleName,
                                           String roleDesc) throws Exception {
        if (StringUtils.isEmpty(roleId) || StringUtils.isEmpty(roleName) || StringUtils.isEmpty(roleDesc)) {
            throw new CommonException("500", "参数为空");
        }
        SpRole spRole = new SpRole();
        spRole.setRoleId(Integer.valueOf(roleId));
        spRole.setRoleName(roleName);
        spRole.setRoleDesc(roleDesc);
        Integer num = spRoleService.updateEntity(spRole);
        if (num == 0) {
            throw new CommonException("500", "修改角色失败");
        }
        return toResultModel("200", "修改角色成功");
    }

    /**
     * @return com.tb.v1.result.ResultJson<java.lang.Object>
     * @Author tangBin
     * @Description 添加角色
     * @Date 2020/7/20 0020 12:32
     * @Param [roleId, roleName, roleDesc]
     **/
    @RequestMapping("/add/role")
    public ResultJson<Object> geAddRole(@RequestBody SpRoleVo vo) throws Exception {
        if (StringUtils.isEmpty(vo.getRoleName()) || StringUtils.isEmpty(vo.getRoleDesc())) {
            throw new CommonException("500", "参数为空");
        }
        SpRole spRole = new SpRole();
        spRole.setRoleName(vo.getRoleName());
        spRole.setRoleDesc(vo.getRoleDesc());
        Integer num = spRoleService.saveEntity(spRole);
        if (num == 0) {
            throw new CommonException("500", "添加角色失败");
        }
        return toResultModel("200", "添加角色成功");
    }


    public static void main(String args[]) {
        String rel = "101";
        String str = "101,0,104,116,115,142,143,144,121,122,123,149,102";
        List<String> list = Arrays.asList(str.split(","));
        List<String> arrayList = new ArrayList<String>(list);
        //System.out.println(arrayList.size()+"=="+arrayList.remove(rel)+"=="+arrayList.size());
        //System.out.println(String.join(",",arrayList));
        List<String> newList = new ArrayList<>();
        newList.add("116");
        newList.add("142");
        System.out.println(arrayList.stream().distinct().count());
    }

}
